<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <!-- 搜索 添加 -->
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input
            placeholder="请输入搜索内容"
            v-model="query.name"
            clearable
            @clear="getUserList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="searchMemberByName"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="3">
          <el-button type="primary" @click="addDialogVisible = true"
            >添加用户</el-button
          >
        </el-col>
        <el-col :span="4">
          <!-- <exportExcel></exportExcel> -->
        </el-col>
      </el-row>
      <!-- 用户列表区域 -->
      <el-table
        id="rebateSetTable"
        :data="userlist"
        border
        stripe
        v-loading="loading"
      >
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="teacherID" label="ID"></el-table-column>
        <el-table-column prop="name" label="姓名"></el-table-column>
        <el-table-column prop="phoneNumber" label="电话"></el-table-column>
        <el-table-column prop="partyBranch" label="党支部"></el-table-column>
        <el-table-column
          prop="isBranchLeader"
          label="是否是党支部领导"
        ></el-table-column>
        <el-table-column
          prop="isPayThisMonth"
          label="本月是否缴纳过党费"
        ></el-table-column>

        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              circle
              @click="showEditDialog(scope.row.teacherID)"
            ></el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              circle
              @click="removeUserByName(scope.row.name)"
            ></el-button>
            <el-tooltip
              class="item"
              effect="dark"
              content="角色分配"
              :enterable="false"
              placement="top"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                circle
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[2, 5, 10, 15]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>

    <!-- 添加用户的对话框 -->
    <el-dialog
      title="添加用户"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogClosed"
    >
      <!-- 内容主体 -->
      <el-form
        :model="addUserForm"
        ref="addUserFormRef"
        :rules="addUserFormRules"
        label-width="100px"
      >
        <el-form-item label="身份证号码" prop="IDNumber">
          <el-input v-model="addUserForm.IDNumber"></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="addUserForm.name"></el-input>
        </el-form-item>
        <el-form-item label="教师卡号" prop="teacherID">
          <el-input v-model="addUserForm.teacherID"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phoneNumber">
          <el-input v-model="addUserForm.phoneNumber"></el-input>
        </el-form-item>
        <el-form-item label="党支部" prop="partyBranch">
          <el-select
            v-model="addUserForm.partyBranch"
            placeholder="请选择党支部"
          >
            <el-option
              v-for="(item, index) in branch"
              :key="index"
              :label="item.name"
              :value="item.name"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否领导" prop="isBranchLeader">
          <el-switch v-model="addUserForm.isBranchLeader"></el-switch>
        </el-form-item>
        <el-form-item label="交钱数" prop="dues">
          <el-input v-model="addUserForm.dues"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改用户的对话框 -->
    <el-dialog
      title="修改党员信息"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClosed"
    >
      <!-- 内容主体 -->
      <el-form
        :model="editUserForm"
        ref="editUserFormRef"
        :rules="editUserFormRules"
        label-width="70px"
      >
        <el-form-item label="用户名">
          <el-input v-model="editUserForm.name" disabled></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phoneNumber">
          <el-input v-model="editUserForm.phoneNumber"></el-input>
        </el-form-item>
        <el-form-item label="党支部" prop="partyBranch">
          <el-select
            v-model="editUserForm.partyBranch"
            placeholder="请选择党支部"
          >
            <el-option
              v-for="(item, index) in branch"
              :key="index"
              :label="item.name"
              :value="item.name"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否领导" prop="isBranchLeader">
          <el-switch v-model="editUserForm.isBranchLeader"></el-switch>
        </el-form-item>
        <el-form-item label="交钱数" prop="dues">
          <el-input v-model="editUserForm.dues"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUser">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import FileSaver from "file-saver";
import XLSX from "xlsx";
import exportExcel from "./ExportExcel";
export default {
  components: {
    // exportExcel,
  },
  data() {
    // 自定义手机号规则
    var checkMobile = (rule, value, callback) => {
      const regMobile = /^1[34578]\d{9}$/;
      if (regMobile.test(value)) {
        return callback();
      }
      // 返回一个错误提示
      callback(new Error("请输入合法的手机号码"));
    };

    //自定义中国身份证规则
    var chinaIdentityValid = (rule, value, callback) => {
      if (!value) {
        return callback();
      }
      let city = {
        11: "北京",
        12: "天津",
        13: "河北",
        14: "山西",
        15: "内蒙古",
        21: "辽宁",
        22: "吉林",
        23: "黑龙江 ",
        31: "上海",
        32: "江苏",
        33: "浙江",
        34: "安徽",
        35: "福建",
        36: "江西",
        37: "山东",
        41: "河南",
        42: "湖北 ",
        43: "湖南",
        44: "广东",
        45: "广西",
        46: "海南",
        50: "重庆",
        51: "四川",
        52: "贵州",
        53: "云南",
        54: "西藏 ",
        61: "陕西",
        62: "甘肃",
        63: "青海",
        64: "宁夏",
        65: "新疆",
        71: "台湾",
        81: "香港",
        82: "澳门",
        91: "国外",
      };
      if (
        !value ||
        !/^\d{6}(18|19|20)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/i.test(
          value
        )
      ) {
        callback(new Error("身份证号格式错误"));
      } else if (!city[value.substr(0, 2)]) {
        callback(new Error("身份证号格式错误"));
      } else {
        // 18位身份证需要验证最后一位校验位
        if (value.length === 18) {
          const code = value.split("");
          // ∑(ai×Wi)(mod 11)
          // 加权因子
          const factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
          // 校验位
          const parity = [1, 0, "X", 9, 8, 7, 6, 5, 4, 3, 2];
          let sum = 0;
          let ai = 0;
          let wi = 0;
          for (let i = 0; i < 17; i++) {
            ai = code[i];
            wi = factor[i];
            sum += ai * wi;
          }
          if (parity[sum % 11].toString() !== code[17]) {
            callback(new Error());
          }
        }
      }
      callback();
    };

    return {
      //加载
      loading: false,
      // 获取用户列表查询参数对象
      queryInfo: {
        //query: "",
        // 当前页数
        pagenum: 1,
        // 每页显示多少数据
        pagesize: 5,
      },
      query: { name: "" },
      userlist: [],
      total: 0,
      // 添加用户对话框
      addDialogVisible: false,
      // 用户添加
      addUserForm: {
        IDNumber: "",
        name: "",
        teacherID: "",
        phoneNumber: "",
        partyBranch: "",
        isBranchLeader: "",
        dues: 0,
      },
      //用户添加中的党支部下拉框数据
      branch: [],
      // 用户添加表单验证规则
      addUserFormRules: {
        IDNumber: [
          { required: true, message: "请输入身份证号码", trigger: "blur" },
          { validator: chinaIdentityValid, trigger: "blur" },
        ],
        name: [
          { required: true, message: "请输入姓名", trigger: "blur" },
          {
            min: 2,
            max: 4,
            message: "姓名的长度在2～4个字",
            trigger: "blur",
          },
        ],
        teacherID: [
          { required: true, message: "请输入教师卡号", trigger: "blur" },
          {
            min: 5,
            max: 5,
            message: "教师卡号长度在5个字",
            trigger: "blur",
          },
        ],
        phoneNumber: [
          { required: true, message: "请输入手机号码", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" },
        ],
      },
      // 修改用户
      editTeacherID: {
        teacherID: "",
      },
      editDialogVisible: false,
      editUserForm: {},
      tempeditUserForm: {
        teacherID: "",
        phoneNumber: "",
        partyBranch: "",
        isBranchLeader: "",
        dues: "",
      },
      // 编辑用户表单验证
      editUserFormRules: {
        phoneNumber: [
          { required: true, message: "请输入手机号码", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" },
        ],
      },
      // 分配角色对话框
      setRoleDialogVisible: false,
      // 当前需要被分配角色的用户
      userInfo: {},
      // 所有角色数据列表
      rolesLsit: [],
      // 已选中的角色Id值
      selectRoleId: "",
    };
  },
  created() {
    this.getUserList();
    this.getBranchs();
  },
  methods: {
    async getUserList() {
      this.loading = true;
      const { data: res } = await this.$http.get("namelist", {
        params: this.queryInfo,
      });
      console.log(res);
      this.userlist = res.partyMemberList;
      this.total = res.total;
      this.loading = false;
    },
    // 监听 pagesize改变的事件
    handleSizeChange(newSize) {
      console.log(newSize);
      this.queryInfo.pagesize = newSize;
      this.getUserList();
    },
    // 监听 页码值 改变事件
    handleCurrentChange(newSize) {
      console.log(newSize);
      this.queryInfo.pagenum = newSize;
      this.getUserList();
    },
    //搜索用户
    async searchMemberByName() {
      //var name=this.query
      const { data: res } = await this.$http.get("searchMemberByName", {
        params: this.query,
      });
      console.log(res);
      this.userlist = res;
      this.total = undefined;
      console.log(this.userlist);
    },
    // 监听 添加用户对话框的关闭事件
    addDialogClosed() {
      this.$refs.addUserFormRef.resetFields();
    },
    //添加用户之前获取初始化党支部下拉框的数据
    async getBranchs() {
      const { data: res } = await this.$http.get("searchAllBranch");
      console.log(res);
      this.branch = res;
    },
    // 添加用户
    addUser() {
      // 提交请求前，表单预验证
      this.$refs.addUserFormRef.validate(async (valid) => {
        // console.log(valid)
        // 表单预校验失败
        if (!valid) return;
        var temp = this.addUserForm;
        if (temp.isBranchLeader === true) {
          temp.isBranchLeader = "是";
        } else {
          temp.isBranchLeader = "否";
        }
        console.log(temp);
        const { data: res } = await this.$http.post(
          "addPartyMember",
          this.$qs.stringify(temp)
        );
        this.$message.success("添加用户成功！");
        // 隐藏添加用户对话框
        this.addDialogVisible = false;
        this.getUserList();
      });
    },
    // 编辑用户信息
    async showEditDialog(id) {
      this.editTeacherID.teacherID = id;
      const { data: res } = await this.$http.get("searchMemberByTeacherID", {
        params: this.editTeacherID,
      });
      console.log(res);
      this.editUserForm = res;
      this.editDialogVisible = true;
    },
    // 监听修改用户对话框的关闭事件
    editDialogClosed() {
      this.$refs.editUserFormRef.resetFields();
    },
    // 修改用户信息
    editUser() {
      // 提交请求前，表单预验证
      this.$refs.editUserFormRef.validate(async (valid) => {
        // console.log(valid)
        // 表单预校验失败
        if (!valid) return;
        this.tempeditUserForm.teacherID = this.editUserForm.teacherID;
        this.tempeditUserForm.phoneNumber = this.editUserForm.phoneNumber;
        this.tempeditUserForm.partyBranch = this.editUserForm.partyBranch;
        this.tempeditUserForm.isBranchLeader = this.editUserForm.isBranchLeader;
        if (this.tempeditUserForm.isBranchLeader === true) {
          this.tempeditUserForm.isBranchLeader = "是";
        } else {
          this.tempeditUserForm.isBranchLeader = "否";
        }
        this.tempeditUserForm.dues = this.editUserForm.dues;
        const { data: res } = await this.$http.put(
          "modifyPartyMember",
          this.$qs.stringify(this.tempeditUserForm)
        );
        // 隐藏添加用户对话框
        this.editDialogVisible = false;
        this.$message.success("更新用户信息成功！");
        this.getUserList();
      });
    },
    // 删除用户
    async removeUserByName(tempName) {
      console.log(tempName);
      const confirmResult = await this.$confirm(
        "此操作将永久删除该用户, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      // 点击确定 返回值为：confirm
      // 点击取消 返回值为： cancel
      if (confirmResult !== "confirm") {
        return this.$message.info("已取消删除");
      }
      console.log(tempName);
      var temp = { name: tempName };
      console.log(temp);
      const { data: res } = await this.$http.delete("deletePartyMember", {
        params: temp,
      });
      this.$message.success("删除用户成功！");
      this.getUserList();
    },
    //导出表格为Excel
    exportExcel() {
      let wb = XLSX.utils.table_to_book(
        document.querySelector("#rebateSetTable")
      );
      let wbout = XLSX.write(wb, {
        bookType: "xlsx",
        bookSST: true,
        type: "array",
      });
      try {
        FileSaver.saveAs(
          new Blob([wbout], { type: "application/octet-stream" }),
          "用户提交返利表.xlsx"
        );
      } catch (e) {
        if (typeof console !== "undefined") console.log(e, wbout);
      }
      return wbout;
    },
  },
};
</script>

<style lang="less" scoped>
</style>
